/*
 * @lc app=leetcode.cn id=1249 lang=typescript
 *
 * [1249] 移除无效的括号
 */

// @lc code=start
function minRemoveToMakeValid(s: string): string {
    let stack: any = [];
    let map = new Map();
    let index = 0;
    for (let i = 0; i < s.length; i++) {
        const count = map.get('(') || 0
        if (s[i] === ')') {
            if (count && count > 0) {
                index++;
                map.set('(', count - 1);
            } else {
                continue
            }
        }
        if (s[i] === '(') {
            map.set(s[i], count + 1);
        }
        stack.push(s[i]);
    }
    let res = '';
    for (let i = 0; i < stack.length; i++) {
        if (stack[i] === '(') {
            index = index - 1;
            if (index < 0) {
                continue;
            }
        }
        res = res + stack[i];
    }
    return res || '';
};

// minRemoveToMakeValid("(a(b(c)d)")
// @lc code=end

